package com.upbos.sso.resolver;

import com.upbos.sso.SsoManager;
import com.upbos.sso.constant.Constants;
import com.upbos.sso.entity.Token;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

public class UserContext {

    protected SsoManager ssoManager;

    protected Token token;

    public UserContext() {
        super();
    }

    public UserContext(SsoManager ssoManager, HttpServletRequest request) {
        this.ssoManager = ssoManager;
        this.token = ssoManager.getToken(request);
    }

    public UserContext(SsoManager ssoManager, Token token) {
        this.ssoManager = ssoManager;
        this.token = token;
    }


    public boolean hasRole(String key) {
        List<String> roles = getUserRole();
        if (roles != null && roles.contains(key)) {
            return true;
        }
        return false;
    }

    public List<String> getUserRole() {
        return token == null ? null : ssoManager.getAttr(token.getId(), Constants.SESSION_KEY_ROLE);
    }

    public boolean hasPrivilege(String key) {
        List<String> privileges = getUserPrivilege();
        if (privileges != null && privileges.contains(key)) {
            return true;
        }
        return false;
    }

    public List<String> getUserPrivilege() {
        return token == null ? null : ssoManager.getAttr(token.getId(), Constants.SESSION_KEY_PRIVILEGE);
    }

    public Token getToken() {
        return token;
    }


    public void setAttr(String key, Object value) {
        ssoManager.setAttr(token.getId(), key, value);
    }


    public <T> T getAttr(String key) {
        return ssoManager.getAttr(token.getId(), key);
    }


    public void removeAttr(String key) {
        ssoManager.removeAttr(token.getId(), key);
    }

}
